<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ project.title }} - 分享演示</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
            overflow: hidden;
            height: 100vh;
            color: white;
        }

        .presentation-container {
            position: relative;
            width: 100vw;
            height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            background: radial-gradient(ellipse at center, rgba(255,255,255,0.1) 0%, rgba(0,0,0,0.3) 100%);
        }

        .slide-display {
            position: relative;
            width: 90vw;
            height: 90vh;
            max-width: calc(90vh * 16/9);
            max-height: calc(90vw * 9/16);
            background: white;
            border-radius: 15px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.4);
            overflow: hidden;
            transition: all 0.3s ease;
        }

        .slide-display:hover {
            transform: scale(1.02);
            box-shadow: 0 25px 80px rgba(0,0,0,0.5);
        }

        /* 幻灯片容器 - 支持多iframe缓存 */
        .slide-frame-container {
            position: relative;
            width: 100%;
            height: 100%;
            border-radius: 15px;
            overflow: hidden;
        }

        .slide-frame {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            border: none;
            border-radius: 15px;
            background: white;
            transition: opacity 0.3s ease;
        }

        .slide-frame.hidden {
            opacity: 0;
            pointer-events: none;
            z-index: 1;
        }

        .slide-frame.visible {
            opacity: 1;
            pointer-events: auto;
            z-index: 2;
        }

        /* 缓存的iframe样式 */
        .slide-frame.cached {
            display: block;
        }

        .slide-frame.not-loaded {
            display: none;
        }

        .presentation-controls {
            position: fixed;
            bottom: 30px;
            left: 50%;
            transform: translateX(-50%);
            display: flex;
            gap: 20px;
            align-items: center;
            background: rgba(0,0,0,0.7);
            padding: 15px 25px;
            border-radius: 50px;
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255,255,255,0.2);
        }

        .control-btn {
            background: rgba(255,255,255,0.2);
            color: white;
            border: none;
            padding: 12px 18px;
            border-radius: 25px;
            cursor: pointer;
            transition: all 0.3s ease;
            font-size: 16px;
            display: flex;
            align-items: center;
            gap: 8px;
            min-width: 50px;
            justify-content: center;
        }

        .control-btn:hover {
            background: rgba(255,255,255,0.3);
            transform: translateY(-2px);
        }

        .control-btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        .slide-counter {
            color: white;
            font-size: 18px;
            font-weight: bold;
            padding: 0 15px;
            background: rgba(255,255,255,0.1);
            border-radius: 20px;
            padding: 8px 16px;
        }

        .presentation-header {
            position: fixed;
            top: 20px;
            left: 50%;
            transform: translateX(-50%);
            background: rgba(0,0,0,0.7);
            padding: 10px 20px;
            border-radius: 25px;
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255,255,255,0.2);
            z-index: 1000;
        }

        .presentation-title {
            color: white;
            font-size: 18px;
            font-weight: bold;
            margin: 0;
        }

        .exit-btn {
            position: fixed;
            top: 20px;
            right: 20px;
            background: rgba(255,0,0,0.7);
            color: white;
            border: none;
            padding: 12px 15px;
            border-radius: 50%;
            cursor: pointer;
            font-size: 18px;
            transition: all 0.3s ease;
            z-index: 1000;
        }

        .exit-btn:hover {
            background: rgba(255,0,0,0.9);
            transform: scale(1.1);
        }

        .slide-thumbnails {
            position: fixed;
            left: 20px;
            top: 50%;
            transform: translateY(-50%);
            display: flex;
            flex-direction: column;
            gap: 10px;
            max-height: 70vh;
            overflow-y: auto;
            background: rgba(0,0,0,0.5);
            padding: 15px;
            border-radius: 15px;
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255,255,255,0.2);
            opacity: 0;
            transition: opacity 0.3s ease;
        }

        .slide-thumbnails.show {
            opacity: 1;
        }

        .thumbnail {
            width: 80px;
            height: 45px;
            border: 2px solid transparent;
            border-radius: 5px;
            cursor: pointer;
            transition: all 0.3s ease;
            overflow: hidden;
            background: white;
            position: relative;
        }

        .thumbnail:hover {
            border-color: #007bff;
            transform: scale(1.1);
        }

        .thumbnail.active {
            border-color: #28a745;
            box-shadow: 0 0 10px rgba(40, 167, 69, 0.5);
        }

        .thumbnail iframe {
            width: 100%;
            height: 100%;
            border: none;
            pointer-events: none;
            transform: scale(0.2);
            transform-origin: top left;
            width: 400px;
            height: 225px;
        }

        .thumbnail-number {
            position: absolute;
            bottom: 2px;
            right: 2px;
            background: rgba(0,0,0,0.7);
            color: white;
            font-size: 10px;
            padding: 2px 4px;
            border-radius: 3px;
        }

        .toggle-thumbnails {
            position: fixed;
            left: 20px;
            bottom: 30px;
            background: rgba(0,0,0,0.7);
            color: white;
            border: none;
            padding: 12px 15px;
            border-radius: 25px;
            cursor: pointer;
            transition: all 0.3s ease;
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255,255,255,0.2);
        }

        .toggle-thumbnails:hover {
            background: rgba(0,0,0,0.9);
        }

        .loading-overlay {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(255,255,255,0.9);
            display: none; /* 默认隐藏，避免初始闪烁 */
            justify-content: center;
            align-items: center;
            border-radius: 15px;
            z-index: 10;
            transition: opacity 0.2s ease;
        }

        .loading-overlay.show {
            display: flex;
            opacity: 1;
        }

        .loading-spinner {
            width: 40px;
            height: 40px;
            border: 3px solid #f3f3f3;
            border-top: 3px solid #007bff;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        /* 平滑过渡效果 */
        .slide-transition {
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        }

        /* 防止iframe白屏闪烁 */
        iframe {
            background-color: white;
            will-change: opacity;
        }

        /* 硬件加速优化 */
        .slide-frame-container,
        .slide-frame {
            transform: translateZ(0);
            backface-visibility: hidden;
            perspective: 1000px;
        }

        /* 预加载优化 */
        .slide-frame.preloading {
            visibility: hidden;
            position: absolute;
            top: -9999px;
            left: -9999px;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .slide-display {
                width: 95vw;
                height: 95vh;
            }

            .presentation-controls {
                bottom: 15px;
                padding: 10px 15px;
                gap: 10px;
            }

            .control-btn {
                padding: 8px 12px;
                font-size: 14px;
            }

            .slide-counter {
                font-size: 14px;
                padding: 6px 12px;
            }

            .slide-thumbnails {
                left: 10px;
                padding: 10px;
            }

            .thumbnail {
                width: 60px;
                height: 34px;
            }

            .toggle-thumbnails {
                left: 10px;
                bottom: 15px;
                padding: 8px 12px;
            }
        }

        /* 键盘快捷键提示 */
        .keyboard-hints {
            position: fixed;
            top: 50%;
            right: 20px;
            transform: translateY(-50%);
            background: rgba(0,0,0,0.7);
            padding: 15px;
            border-radius: 10px;
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255,255,255,0.2);
            opacity: 0;
            transition: opacity 0.3s ease;
            font-size: 12px;
        }

        .keyboard-hints.show {
            opacity: 1;
        }

        .keyboard-hints h6 {
            color: #007bff;
            margin-bottom: 10px;
        }

        .keyboard-hints div {
            margin-bottom: 5px;
        }

        .key {
            background: rgba(255,255,255,0.2);
            padding: 2px 6px;
            border-radius: 3px;
            font-family: monospace;
        }

        /* 缓存状态面板 */
        .cache-status {
            position: fixed;
            bottom: 80px;
            right: 20px;
            background: rgba(0,0,0,0.8);
            color: white;
            padding: 10px;
            border-radius: 8px;
            font-size: 11px;
            font-family: monospace;
            opacity: 0;
            transition: opacity 0.3s ease;
            z-index: 1000;
            min-width: 200px;
        }

        .cache-status.show {
            opacity: 1;
        }

        .cache-status h6 {
            color: #4caf50;
            margin: 0 0 8px 0;
            font-size: 12px;
        }

        .cache-status .stat-line {
            margin-bottom: 4px;
            display: flex;
            justify-content: space-between;
        }

        .cache-status .stat-value {
            color: #81c784;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <div class="presentation-container">
        <!-- 演示标题 -->
        <div class="presentation-header">
            <h5 class="presentation-title">{{ project.title }}</h5>
        </div>

        <!-- 退出按钮 -->
        <button class="exit-btn" onclick="exitPresentation()" title="退出演示 (ESC)">
            <i class="fas fa-times"></i>
        </button>

        <!-- 主要幻灯片显示区域 -->
        <div class="slide-display">
            <div class="loading-overlay" id="loadingOverlay">
                <div class="loading-spinner"></div>
            </div>
            <div class="slide-frame-container" id="slideFrameContainer">
                <!-- iframe将动态创建和管理 -->
            </div>
        </div>

        <!-- 演示控制栏 -->
        <div class="presentation-controls">
            <button class="control-btn" id="prevBtn" onclick="previousSlide()" title="上一页 (←)">
                <i class="fas fa-chevron-left"></i>
            </button>
            
            <button class="control-btn" onclick="toggleAutoPlay()" id="autoPlayBtn" title="自动播放">
                <i class="fas fa-play"></i>
            </button>
            
            <div class="slide-counter" id="slideCounter">1 / {{ slides_count }}</div>
            
            <button class="control-btn" onclick="toggleFullscreen()" title="全屏 (F)">
                <i class="fas fa-expand"></i>
            </button>
            
            <button class="control-btn" id="nextBtn" onclick="nextSlide()" title="下一页 (→)">
                <i class="fas fa-chevron-right"></i>
            </button>
        </div>

        <!-- 缩略图切换按钮 -->
        <button class="toggle-thumbnails" onclick="toggleThumbnails()" title="显示/隐藏缩略图 (T)">
            <i class="fas fa-th-large"></i>
        </button>

        <!-- 幻灯片缩略图 -->
        <div class="slide-thumbnails" id="slideThumbnails">
            {% for slide in project.slides_data %}
            <div class="thumbnail {% if loop.index == 1 %}active{% endif %}" 
                 onclick="goToSlide({{ loop.index0 }})" 
                 data-slide-index="{{ loop.index0 }}">
                <iframe srcdoc="{{ slide.html_content | e }}" title="Slide {{ loop.index }}"></iframe>
                <div class="thumbnail-number">{{ loop.index }}</div>
            </div>
            {% endfor %}
        </div>

        <!-- 键盘快捷键提示 -->
        <div class="keyboard-hints" id="keyboardHints">
            <h6><i class="fas fa-keyboard"></i> 快捷键</h6>
            <div><span class="key">←/→</span> 上一页/下一页</div>
            <div><span class="key">Space</span> 下一页</div>
            <div><span class="key">F</span> 全屏切换</div>
            <div><span class="key">T</span> 缩略图</div>
            <div><span class="key">H</span> 显示/隐藏帮助</div>
            <div><span class="key">C</span> 缓存状态</div>
            <div><span class="key">ESC</span> 退出演示</div>
        </div>

        <!-- 缓存状态面板 -->
        <div class="cache-status" id="cacheStatus">
            <h6><i class="fas fa-memory"></i> 缓存状态</h6>
            <div class="stat-line">
                <span>已缓存:</span>
                <span class="stat-value" id="cachedCount">0</span>
            </div>
            <div class="stat-line">
                <span>加载中:</span>
                <span class="stat-value" id="loadingCount">0</span>
            </div>
            <div class="stat-line">
                <span>缓存率:</span>
                <span class="stat-value" id="cacheRatio">0%</span>
            </div>
            <div class="stat-line">
                <span>总页数:</span>
                <span class="stat-value" id="totalCount">0</span>
            </div>
        </div>


    </div>

    <script>
        // 全局变量
        let currentSlideIndex = 0;
        let totalSlides = {{ slides_count }};
        let slidesData = {{ project.slides_data | tojson }};
        let autoPlayInterval = null;
        let isAutoPlaying = false;
        let thumbnailsVisible = false;
        let keyboardHintsVisible = false;

        // 缓存机制相关变量
        let slideFrameCache = new Map(); // 缓存已渲染的iframe: slideIndex -> iframe元素
        let currentVisibleFrame = null; // 当前显示的iframe
        let isTransitioning = false; // 是否正在切换中
        let loadingSlides = new Set(); // 正在加载的幻灯片索引
        let frameIdCounter = 0; // iframe ID计数器

        // 初始化演示
        document.addEventListener('DOMContentLoaded', function() {
            initializePresentation();
            updateControls();

            // 启动定期检查数据更新
            startDataRefreshCheck();
        });

        // 初始化演示系统
        function initializePresentation() {
            console.log('初始化演示系统，总幻灯片数:', totalSlides);

            // 加载第一张幻灯片
            loadSlideWithCache(0, true);

            // 预加载前几张幻灯片以提升体验
            setTimeout(() => {
                preloadAdjacentSlides(0);
            }, 1000);
        }

        // 定期检查数据更新
        function startDataRefreshCheck() {
            setInterval(async () => {
                try {
                    const response = await fetch(`/api/projects/{{ project.project_id }}/slides-data`);
                    const data = await response.json();

                    if (data.status === 'success' && data.updated_at > {{ project.updated_at }}) {
                        // 数据已更新，刷新幻灯片数据
                        console.log('检测到幻灯片数据更新，正在刷新...');
                        slidesData = data.slides_data;
                        totalSlides = data.total_slides;

                        // 清空所有缓存
                        clearAllCache();

                        // 重新加载当前幻灯片
                        loadSlideWithCache(currentSlideIndex, true);

                        // 更新缩略图
                        updateThumbnailsContent();

                        // 显示更新提示
                        showUpdateNotification();
                    }
                } catch (error) {
                    console.warn('检查数据更新失败:', error);
                }
            }, 10000); // 每10秒检查一次
        }

        // 更新缩略图内容
        function updateThumbnailsContent() {
            const thumbnailsContainer = document.getElementById('slideThumbnails');
            thumbnailsContainer.innerHTML = '';

            slidesData.forEach((slide, index) => {
                const thumbnailDiv = document.createElement('div');
                thumbnailDiv.className = `thumbnail ${index === currentSlideIndex ? 'active' : ''}`;
                thumbnailDiv.onclick = () => goToSlide(index);
                thumbnailDiv.setAttribute('data-slide-index', index);

                thumbnailDiv.innerHTML = `
                    <iframe srcdoc="${slide.html_content.replace(/"/g, '&quot;')}" title="Slide ${index + 1}"></iframe>
                    <div class="thumbnail-number">${index + 1}</div>
                `;

                thumbnailsContainer.appendChild(thumbnailDiv);
            });
        }

        // 显示更新通知
        function showUpdateNotification() {
            const notification = document.createElement('div');
            notification.style.cssText = `
                position: fixed;
                top: 80px;
                right: 20px;
                background: rgba(40, 167, 69, 0.9);
                color: white;
                padding: 10px 15px;
                border-radius: 5px;
                z-index: 2000;
                font-size: 14px;
                backdrop-filter: blur(10px);
                border: 1px solid rgba(255,255,255,0.2);
            `;
            notification.innerHTML = '<i class="fas fa-sync"></i> 幻灯片内容已更新';

            document.body.appendChild(notification);

            setTimeout(() => {
                notification.remove();
            }, 3000);
        }

        // 使用缓存机制加载幻灯片
        function loadSlideWithCache(index, isInitial = false) {
            if (index < 0 || index >= totalSlides || isTransitioning) return;

            // 如果是相同的幻灯片，直接返回
            if (index === currentSlideIndex && !isInitial) return;

            console.log(`加载幻灯片 ${index + 1}/${totalSlides}:`, slidesData[index]?.title);

            isTransitioning = true;

            // 检查是否已缓存
            if (slideFrameCache.has(index)) {
                // 使用缓存的iframe
                const cachedFrame = slideFrameCache.get(index);
                switchToFrame(cachedFrame, index);
            } else {
                // 创建新的iframe并渲染
                createAndLoadFrame(index, isInitial);
            }
        }

        // 创建并加载新的iframe
        function createAndLoadFrame(index, isInitial = false) {
            if (loadingSlides.has(index)) return; // 防止重复加载

            loadingSlides.add(index);

            if (isInitial) {
                showLoadingOverlay();
            }

            const frameId = `slideFrame_${frameIdCounter++}`;
            const iframe = document.createElement('iframe');
            iframe.id = frameId;
            iframe.className = 'slide-frame hidden not-loaded';
            iframe.title = `PPT Slide ${index + 1}`;

            // 设置内容
            if (slidesData[index] && slidesData[index].html_content) {
                iframe.srcdoc = slidesData[index].html_content;

                // 监听加载完成
                iframe.onload = function() {
                    console.log(`幻灯片 ${index + 1} 渲染完成`);

                    // 缓存iframe
                    slideFrameCache.set(index, iframe);
                    loadingSlides.delete(index);

                    // 更新样式
                    iframe.classList.remove('not-loaded');
                    iframe.classList.add('cached');

                    // 延迟一点确保内容完全渲染
                    setTimeout(() => {
                        switchToFrame(iframe, index);
                    }, 100);
                };

                iframe.onerror = function() {
                    console.error(`幻灯片 ${index + 1} 加载失败`);
                    loadingSlides.delete(index);
                    isTransitioning = false;
                    hideLoadingOverlay();
                };

                // 添加到容器
                document.getElementById('slideFrameContainer').appendChild(iframe);
            } else {
                console.error(`幻灯片 ${index + 1} 数据无效`);
                loadingSlides.delete(index);
                isTransitioning = false;
                hideLoadingOverlay();
            }
        }

        // 切换到指定的iframe
        function switchToFrame(targetFrame, index) {
            // 隐藏当前显示的iframe
            if (currentVisibleFrame) {
                currentVisibleFrame.classList.remove('visible');
                currentVisibleFrame.classList.add('hidden');
            }

            // 显示目标iframe
            targetFrame.classList.remove('hidden');
            targetFrame.classList.add('visible');

            // 更新状态
            currentVisibleFrame = targetFrame;
            currentSlideIndex = index;
            isTransitioning = false;

            // 更新UI
            updateControls();
            updateThumbnails();
            hideLoadingOverlay();

            // 预加载相邻幻灯片
            setTimeout(() => {
                preloadAdjacentSlides(index);
                // 管理缓存大小
                manageCacheSize();
            }, 300);

            const stats = getCacheStats();
            console.log(`切换到幻灯片 ${index + 1}，缓存统计:`, stats);
        }

        // 预加载相邻幻灯片
        function preloadAdjacentSlides(currentIndex) {
            const preloadIndices = [];

            // 预加载策略：当前页前后各2页
            for (let i = Math.max(0, currentIndex - 2); i <= Math.min(totalSlides - 1, currentIndex + 2); i++) {
                if (i !== currentIndex && !slideFrameCache.has(i) && !loadingSlides.has(i)) {
                    preloadIndices.push(i);
                }
            }

            // 分批预加载，避免同时加载太多
            preloadIndices.forEach((index, i) => {
                setTimeout(() => {
                    preloadSlide(index);
                }, i * 200); // 每200ms预加载一个
            });
        }

        // 预加载单个幻灯片
        function preloadSlide(index) {
            if (index < 0 || index >= totalSlides || slideFrameCache.has(index) || loadingSlides.has(index)) {
                return;
            }

            console.log(`预加载幻灯片 ${index + 1}`);

            loadingSlides.add(index);

            const frameId = `slideFrame_${frameIdCounter++}`;
            const iframe = document.createElement('iframe');
            iframe.id = frameId;
            iframe.className = 'slide-frame hidden not-loaded';
            iframe.title = `PPT Slide ${index + 1}`;

            if (slidesData[index] && slidesData[index].html_content) {
                iframe.srcdoc = slidesData[index].html_content;

                iframe.onload = function() {
                    console.log(`预加载完成: 幻灯片 ${index + 1}`);
                    slideFrameCache.set(index, iframe);
                    loadingSlides.delete(index);

                    iframe.classList.remove('not-loaded');
                    iframe.classList.add('cached');
                };

                iframe.onerror = function() {
                    console.error(`预加载失败: 幻灯片 ${index + 1}`);
                    loadingSlides.delete(index);
                };

                // 添加到容器
                document.getElementById('slideFrameContainer').appendChild(iframe);
            } else {
                loadingSlides.delete(index);
            }
        }

        // 显示加载动画
        function showLoadingOverlay() {
            const loadingOverlay = document.getElementById('loadingOverlay');
            loadingOverlay.classList.add('show');
        }

        // 隐藏加载动画
        function hideLoadingOverlay() {
            const loadingOverlay = document.getElementById('loadingOverlay');
            loadingOverlay.classList.remove('show');
        }

        // 清空所有缓存
        function clearAllCache() {
            console.log('清空所有幻灯片缓存');

            // 移除所有缓存的iframe
            slideFrameCache.forEach((iframe, index) => {
                if (iframe.parentNode) {
                    iframe.parentNode.removeChild(iframe);
                }
            });

            // 清空缓存映射
            slideFrameCache.clear();
            loadingSlides.clear();
            currentVisibleFrame = null;

            console.log('缓存清空完成');
        }

        // 获取缓存统计信息
        function getCacheStats() {
            return {
                cachedSlides: slideFrameCache.size,
                loadingSlides: loadingSlides.size,
                totalSlides: totalSlides,
                cacheRatio: (slideFrameCache.size / totalSlides * 100).toFixed(1) + '%'
            };
        }

        // 智能缓存管理 - 限制缓存数量以节省内存
        function manageCacheSize() {
            const maxCacheSize = Math.min(10, totalSlides); // 最多缓存10个幻灯片

            if (slideFrameCache.size > maxCacheSize) {
                // 移除距离当前页面最远的缓存
                const sortedIndices = Array.from(slideFrameCache.keys()).sort((a, b) => {
                    const distA = Math.abs(a - currentSlideIndex);
                    const distB = Math.abs(b - currentSlideIndex);
                    return distB - distA; // 距离远的排在前面
                });

                // 移除最远的缓存
                const toRemove = sortedIndices.slice(0, slideFrameCache.size - maxCacheSize + 1);
                toRemove.forEach(index => {
                    const iframe = slideFrameCache.get(index);
                    if (iframe && iframe !== currentVisibleFrame) {
                        if (iframe.parentNode) {
                            iframe.parentNode.removeChild(iframe);
                        }
                        slideFrameCache.delete(index);
                        console.log(`移除缓存: 幻灯片 ${index + 1}`);
                    }
                });
            }
        }

        // 兼容旧的loadSlide函数
        function loadSlide(index) {
            loadSlideWithCache(index);
        }

        // 更新控制按钮状态
        function updateControls() {
            const prevBtn = document.getElementById('prevBtn');
            const nextBtn = document.getElementById('nextBtn');
            const slideCounter = document.getElementById('slideCounter');

            prevBtn.disabled = currentSlideIndex === 0;
            nextBtn.disabled = currentSlideIndex === totalSlides - 1;
            slideCounter.textContent = `${currentSlideIndex + 1} / ${totalSlides}`;
        }

        // 更新缩略图状态
        function updateThumbnails() {
            const thumbnails = document.querySelectorAll('.thumbnail');
            thumbnails.forEach((thumb, index) => {
                thumb.classList.toggle('active', index === currentSlideIndex);
            });
        }

        // 上一页
        function previousSlide() {
            if (currentSlideIndex > 0 && !isTransitioning) {
                loadSlideWithCache(currentSlideIndex - 1);
            }
        }

        // 下一页
        function nextSlide() {
            if (currentSlideIndex < totalSlides - 1 && !isTransitioning) {
                loadSlideWithCache(currentSlideIndex + 1);
            }
        }

        // 跳转到指定幻灯片
        function goToSlide(index) {
            if (!isTransitioning && index !== currentSlideIndex && index >= 0 && index < totalSlides) {
                loadSlideWithCache(index);
            }
        }

        // 切换自动播放
        function toggleAutoPlay() {
            const autoPlayBtn = document.getElementById('autoPlayBtn');

            if (isAutoPlaying) {
                clearInterval(autoPlayInterval);
                autoPlayBtn.innerHTML = '<i class="fas fa-play"></i>';
                autoPlayBtn.title = '自动播放';
                isAutoPlaying = false;
            } else {
                autoPlayInterval = setInterval(() => {
                    if (currentSlideIndex < totalSlides - 1) {
                        nextSlide();
                    } else {
                        // 到达最后一页，停止自动播放
                        toggleAutoPlay();
                    }
                }, 5000); // 5秒间隔

                autoPlayBtn.innerHTML = '<i class="fas fa-pause"></i>';
                autoPlayBtn.title = '暂停自动播放';
                isAutoPlaying = true;
            }
        }

        // 切换全屏
        function toggleFullscreen() {
            if (!document.fullscreenElement) {
                document.documentElement.requestFullscreen().catch(err => {
                    console.log('无法进入全屏模式:', err);
                });
            } else {
                if (document.exitFullscreen) {
                    document.exitFullscreen();
                }
            }
        }

        // 切换缩略图显示
        function toggleThumbnails() {
            const thumbnails = document.getElementById('slideThumbnails');
            thumbnailsVisible = !thumbnailsVisible;
            thumbnails.classList.toggle('show', thumbnailsVisible);
        }

        // 切换键盘快捷键提示
        function toggleKeyboardHints() {
            const hints = document.getElementById('keyboardHints');
            keyboardHintsVisible = !keyboardHintsVisible;
            hints.classList.toggle('show', keyboardHintsVisible);
        }

        // 切换缓存状态显示
        let cacheStatusVisible = false;
        function toggleCacheStatus() {
            const cacheStatus = document.getElementById('cacheStatus');
            cacheStatusVisible = !cacheStatusVisible;
            cacheStatus.classList.toggle('show', cacheStatusVisible);

            if (cacheStatusVisible) {
                updateCacheStatusDisplay();
                // 定期更新缓存状态
                const updateInterval = setInterval(() => {
                    if (cacheStatusVisible) {
                        updateCacheStatusDisplay();
                    } else {
                        clearInterval(updateInterval);
                    }
                }, 1000);
            }
        }

        // 更新缓存状态显示
        function updateCacheStatusDisplay() {
            const stats = getCacheStats();
            document.getElementById('cachedCount').textContent = stats.cachedSlides;
            document.getElementById('loadingCount').textContent = stats.loadingSlides;
            document.getElementById('cacheRatio').textContent = stats.cacheRatio;
            document.getElementById('totalCount').textContent = stats.totalSlides;
        }

        // 退出演示
        function exitPresentation() {
            // 停止自动播放
            if (isAutoPlaying) {
                toggleAutoPlay();
            }

            // 退出全屏
            if (document.fullscreenElement) {
                document.exitFullscreen();
            }

        }

        // 键盘事件处理（防抖）
        let keyboardDebounce = false;
        document.addEventListener('keydown', function(e) {
            // 防止在切换过程中重复触发
            if (isTransitioning) return;

            switch(e.key) {
                case 'ArrowLeft':
                    e.preventDefault();
                    if (!keyboardDebounce) {
                        keyboardDebounce = true;
                        previousSlide();
                        setTimeout(() => keyboardDebounce = false, 200);
                    }
                    break;
                case 'ArrowRight':
                case ' ':
                    e.preventDefault();
                    if (!keyboardDebounce) {
                        keyboardDebounce = true;
                        nextSlide();
                        setTimeout(() => keyboardDebounce = false, 200);
                    }
                    break;
                case 'f':
                case 'F':
                    e.preventDefault();
                    toggleFullscreen();
                    break;
                case 't':
                case 'T':
                    e.preventDefault();
                    toggleThumbnails();
                    break;
                case 'h':
                case 'H':
                    e.preventDefault();
                    toggleKeyboardHints();
                    break;
                case 'c':
                case 'C':
                    e.preventDefault();
                    toggleCacheStatus();
                    break;
                case 'Escape':
                    e.preventDefault();
                    exitPresentation();
                    break;
                case 'Home':
                    e.preventDefault();
                    if (!keyboardDebounce) {
                        keyboardDebounce = true;
                        goToSlide(0);
                        setTimeout(() => keyboardDebounce = false, 200);
                    }
                    break;
                case 'End':
                    e.preventDefault();
                    if (!keyboardDebounce) {
                        keyboardDebounce = true;
                        goToSlide(totalSlides - 1);
                        setTimeout(() => keyboardDebounce = false, 200);
                    }
                    break;
            }
        });

        // 鼠标滚轮事件（防抖）
        let wheelDebounce = false;
        document.addEventListener('wheel', function(e) {
            if (isTransitioning || wheelDebounce) return;

            e.preventDefault();
            wheelDebounce = true;

            if (e.deltaY > 0) {
                nextSlide();
            } else {
                previousSlide();
            }

            setTimeout(() => wheelDebounce = false, 300);
        });

        // 触摸事件支持（移动设备）
        let touchStartX = 0;
        let touchEndX = 0;
        let touchDebounce = false;

        document.addEventListener('touchstart', function(e) {
            if (isTransitioning) return;
            touchStartX = e.changedTouches[0].screenX;
        });

        document.addEventListener('touchend', function(e) {
            if (isTransitioning || touchDebounce) return;
            touchEndX = e.changedTouches[0].screenX;
            handleSwipe();
        });

        function handleSwipe() {
            const swipeThreshold = 50;
            const diff = touchStartX - touchEndX;

            if (Math.abs(diff) > swipeThreshold) {
                touchDebounce = true;

                if (diff > 0) {
                    // 向左滑动，下一页
                    nextSlide();
                } else {
                    // 向右滑动，上一页
                    previousSlide();
                }

                setTimeout(() => touchDebounce = false, 300);
            }
        }

        // 全屏状态变化监听
        document.addEventListener('fullscreenchange', function() {
            const fullscreenBtn = document.querySelector('[onclick="toggleFullscreen()"]');
            if (document.fullscreenElement) {
                fullscreenBtn.innerHTML = '<i class="fas fa-compress"></i>';
                fullscreenBtn.title = '退出全屏';
            } else {
                fullscreenBtn.innerHTML = '<i class="fas fa-expand"></i>';
                fullscreenBtn.title = '全屏';
            }
        });

        // 防止右键菜单
        document.addEventListener('contextmenu', function(e) {
            e.preventDefault();
        });

        // 页面可见性变化时暂停自动播放
        document.addEventListener('visibilitychange', function() {
            if (document.hidden && isAutoPlaying) {
                toggleAutoPlay();
            }
        });
    </script>
</body>
</html>
